package com.example.module_motocircle.motocircle

import androidx.paging.Pager
import androidx.paging.PagingConfig
import com.example.module_motocircle.adpater.PostPageSource
import com.example.module_motocircle.api.MotocircleApi
import com.example.module_motocircle.api.MotocircleModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import javax.inject.Inject

class MotocircleRepository @Inject constructor() {
    @Inject
    @MotocircleModel.CommonApi
    lateinit var api: MotocircleApi
    fun getNavigationItem() = flow {
        emit(api.getNavigationItem())
    }
    /**
     * 帖子列表
     */
    fun pageList(
        sortBy: String? = null,
        topicId: String? = null,
        memberId: String? = null,
        ifFocus: Int? = null,
        pageNum: Int,
        pageSize: Int = 10,
        keyword: String? = null
    ) = flow {
        emit(
            api.getPostData(
                sortBy,
                topicId,
                memberId,
                ifFocus,
                pageNum,
                pageSize,
                keyword
            )
        )
    }.flowOn(Dispatchers.IO)
    fun queryPostPage(
        isFocus: Int? = null,
        keyword: String? = null,
        memberId: String? = null,
        sortType: String? = null,
        topicId: String? = null
    ) = Pager(
        config = PagingConfig(pageSize = 10),
        pagingSourceFactory = {
            PostPageSource(
                api = api,
                ifFocus = isFocus,
                keyword = keyword,
                memberId = memberId,
                sortType = sortType,
                topicId = topicId
            )
        })
        .flow
    /**
     *  检查是否关注
     */
    fun checkIfHasFocus() = flow {
        emit(api.checkIfHasFocus())
    }.flowOn(Dispatchers.IO)
    /**
     * 点赞取消点赞帖子
     */
    fun giveLike(postsId: String) = flow{
        emit(api.giveValidationLike(postsId))//校验帖子
    }.map {
        if (it.data){//校验通过
            api.giveLike(postsId)
        }else{//校验不通过
            it
        }
    }.flowOn(Dispatchers.IO)
    /**
     * 关键词搜索
     */
    fun searchKeywordList(keyword:String) = flow {
        emit(api.searchKeywordList(keyword))
    }.flowOn(Dispatchers.IO)
    /**
     * 帖子详情
     */
    fun getDetailInfo() = flow{
        emit(api.getDetailInfo())
    }.flowOn(Dispatchers.IO)
    /**
     * 帖子评论
     */
    fun getCommentInfo(pageNum: Int, pageSize: Int = 10) = flow {
        emit(api.getCommentInfo(pageNum,pageSize))
    }.flowOn(Dispatchers.IO)
}